﻿using System;
using System.Windows;

namespace BrasilFramework.Controle.WPF.Comum.Validacao
{
	public class RangeValidator : ValidatorBase
	{
	    public double Min
		{
			get { return (double)GetValue(MinProperty); }
			set { SetValue(MinProperty, value); }
		}

        public static readonly DependencyProperty MinProperty =
			DependencyProperty.Register("Min", typeof(double), typeof(RangeValidator), new PropertyMetadata(double.MinValue));
		
		public double Max
		{
			get { return (double)GetValue(MaxProperty); }
			set { SetValue(MaxProperty, value); }
		}
		
		public static readonly DependencyProperty MaxProperty =
			DependencyProperty.Register("Max", typeof(double), typeof(RangeValidator), new PropertyMetadata(double.MaxValue));

        public TextBoxFilterService.TipoFiltro Filter
		{
            get { return (TextBoxFilterService.TipoFiltro)GetValue(FilterProperty); }
			set { SetValue(FilterProperty, value); }
		}

        public static readonly DependencyProperty FilterProperty =
            DependencyProperty.Register("Filter", typeof(TextBoxFilterService.TipoFiltro), typeof(RangeValidator), new PropertyMetadata(TextBoxFilterService.TipoFiltro.Nenhum, FilterChanged));

        private static void FilterChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            RangeValidator validador = ((RangeValidator)sender);
            TextBoxFilterService.SetFilter(validador.ElementToValidate, validador.Filter);
        }

		public override void ActivateValidationRoutine()
		{
			base.ActivateValidationRoutine();
			TextBoxFilterService.SetFilter(ElementToValidate, Filter);
		}
		
		protected override bool ValidateControl()
		{
			if (ElementToValidate is System.Windows.Controls.TextBox)
			{
				string txt = (ElementToValidate as System.Windows.Controls.TextBox).Text;
				if(String.IsNullOrEmpty(txt)) return true;

				double d;
				if (!double.TryParse((ElementToValidate as System.Windows.Controls.TextBox).Text, out d))
				{
					return false;
				}
				return d >= Min && d <= Max;
			}
			return true;
		}
	}
}
